package com.itheima.ydd.interceptor;

import com.itheima.ydd.common.BaseContext;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置拦截器，根据token判断是否登录
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String token = request.getHeader("x-token");
        //判断token是否有效
        boolean flag = JwtUtils.verifyToken(token);
        //token失效返回状态码401，并拦截
        if (!flag) {
            response.setStatus(401);
            return false;
        }
        //token正常，放行
        //解析token，获取id和手机号码
        Claims claims = JwtUtils.getClaims(token);
        String id = (String) claims.get("id");
        String roleId = (String) claims.get("roleId");

        //将user对象存入threadlocal中
        User user = new User();
        user.setId(id);
        user.setRoleId(roleId);
        BaseContext.set(user);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();
    }

}
